package otimista.threads;

import java.util.Map;
import java.util.Random;

import util.Storage;
import util.Table;

public class Consumer implements Runnable {

	private final Table table;
	private final int iterations;
	
	public Consumer(Table table, int iterations) {
		this.table = table;
		this.iterations = iterations;
	}

	@Override
	public void run() {
		try {
			readSomeValues();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void readSomeValues() throws InterruptedException {
		int temp = 0;
		while (temp < this.iterations) {
			String read = readValue();
			if ( read == null ) {
				continue;
			}
			readValue();
			temp++;
		}
	}

	public String readValue() {
		Map<Integer, Storage<String>> tempMap = table.getMap();
		Random random = new Random();
		int randomKey = random.nextInt(tempMap.size());
		Storage<String> storage = tempMap.get(randomKey);
		
		if (storage == null) {
			return null;
		}
		
		try{
			storage.getReadLock().lock();
			return storage.getValue();
		}finally{
			storage.getReadLock().unlock();
		}
	}
}
